Skip to main content

Chapter 20 - Terraform Remote State


Storing the state file securely.

Locking:


https://developer.hashicorp.com/terraform/language/v1.1.x/state/locking A remote state backend location must have a state locking feature

Azure Storage Account


https://developer.hashicorp.com/terraform/language/settings/backends/azurerm Azure Storage accounts support locking in the terms of "leasing" your file out. Once someone makes a connection to it, it leases it out and doesn't allow anyone else to access it.

Code:

terraform {
required_version = ">= 1.0.0"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "> 4.0"
}
}

backend "azurerm" {
resource_group_name = "TerraformStorage_RG"
storage_account_name = "terraformstatesa12345"
container_name = "whereterraformfstatefilesgo"
key = "terraform.tfstate"
}
}

AWS S3 Bucket


https://developer.hashicorp.com/terraform/language/settings/backends/s3 Using an AWS backend for remote state gives you the ability to use locking for your terraform.state file. This is used in combination with DynamoDB to provide state locking. I personally prefer S3 buckets over Azure Storage simply because of the difference in clouds. S3 buckets aren't connected to your existing infrastructure, accessed only by unique keys which make it harder to be manipulated by Azure.

Code

terraform {
backend "s3" {
bucket = "mybucket"
key = "path/to/my/key"
region = "us-east-1"
}
}

Managing configuration drift


https://developer.hashicorp.com/terraform/tutorials/state/resource-drift https://www.hashicorp.com/resources/how-can-i-prevent-configuration-drift https://www.hashicorp.com/blog/detecting-and-managing-drift-with-terraform

Refresh only


Refresh-only is part of the Terraform planning modes You would want to use the terraform plan -refresh-only or terraform apply -refresh-only commands in order to not unintentionally recreate (destroy) resources.

You can use terraform apply -replace=newresource to replace your infrastructure with another instance. https://developer.hashicorp.com/terraform/cli/commands/plan#planning-options

Terraform Import


Resources not currently managed by terraform would need to be imported. As an example, if you have a resource group that contains resources, importing the resource group would then need to have all of the child resources imported. If you run a terraform destroy against a resource group, it will tell you 1 to destroy but in reality, could be thousands of resources.